#!/usr/bin/python
# pylint: disable-msg = C0301

"""This file contains the error functions for pydownloads"""
from settings import DJANGO_PATH, HTTPPATH, DEBUG

class Warn:
    """This class is used to report warnings to users"""
    def __init__(self):
        """This function initialises the warning database."""
        # {level:[warning1,warning2]}
        self.warnings = {1:[], 2:[], 3:[], 4:[]}
        
    def add_warning(self, warning, level=1):
        """This function adds a warning to the database. level is about how important the warning is, 1 - 4 where 1 is the most important"""
        # Only add if warning is not already in db
        # Try to add it to the right level
        if warning not in self.warnings[level]:
            self.warnings[level].append(warning)
    
    def get_warnings(self, levels, output="text"):
        """This function returns a list of warnings based on the levels wanted and whether levels should be cumulative. If output is html, new lines will be converted."""
        returned_warnings = []
        # If the levels variable is a single integer, return the errors for that level and below
        if type(levels) == type(1):
            levels = range(1, levels + 1)
        # Add all the levels in the levels list to the the returned list
        for level in levels:
            # Only add the level if it has warnings attributed to it
            if len(self.warnings[level]) != 0:
                # If the output needs br and p tags rather than new lines
                if output == "html":
                    # Replace all the new lines with line breaks and paragraph breaks
                    level_warnings = []
                    for warning in self.warnings[level]:
                        level_warnings.append(warning.replace('\n\n','<p />').replace('\n','<br />'))
                returned_warnings.append((level, level_warnings))
        return returned_warnings
    

def user_error(u_error, start=False):
    """The user error is output whether DEBUG is True or not.
    For this reason, it should only be used to display data-insensitive errors
    It will cause a stylised error. If start is set,
    html headers are also output."""
    import sys
    # If the script is run manually, just print the error as normal
    if __name__ == "__main__":
        print "Error: " + u_error
    else: # Otherwise, add html formatting and then print
        # This is needed so that django doesn't complain
        import os
        # We first try to import django as it could be installed system wide
        try:
            import django
        except ImportError: # If that fails, we import it from its local path
            # This is needed so that django doesn't complain
            os.environ['DJANGO_SETTINGS_MODULE'] = "settings"
            # Add django to python's path
            sys.path.insert(0, DJANGO_PATH)
        # Now try importing django
        try:
            # Get django template classes
            from django.template import Context, TemplateDoesNotExist
            from django.template.loader import get_template
        except ImportError:
            # If this fails, throw a simple error and quit.
            simple_error("Django not found. Please add the django path to DJANGO_PATH in settings.py")
        # Open the Error template
        try:
            template = get_template('error.html')
        except TemplateDoesNotExist:
            simple_error("The template for the error function does not exist! Please create a file called error.html in a template directory (defined in settings.py).")
        context = {'error':u_error.replace('\n\n', '<p />').replace('\n', '<br />'), 'site':{'httppath':HTTPPATH}}
        # Compile the context dictionary
        context = Context(context)
        # Print the page
        if start:
            print "Content-type: text/html; charset=utf-8\n\n"
        print template.render(context)
    sys.exit()

def error(e_error, start=False):
    """This function will cause an error and stop the program only if DEBUG is True"""
    if DEBUG:
        user_error(e_error, start)

def simple_error(error):
    import sys
    print "Content-Type: text/plain\n\n" + error
    sys.exit()
    
